import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/stores'
import {
  addCartListAPI,
  getCartListAPI,
  deleteCartListAPI,
  updateCartListAPI
} from '@/apis/cart'
import userInfo from '@/views/Member/components/UserInfo.vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 获取token
    const userStore = useUserStore()
    const isLogin = userStore.isLogin
    const updateCartList = async () => {
      const res = await getCartListAPI(userStore.userInfo.data.user.id)
      cartList.value = res.data.data
      console.log(cartList.value)
    }
    // 定义state
    const cartList = ref([])
    // 定义action
    // 添加购物车
    const addCart = async (goods) => {
      // 判断是否登录
      const goodId = goods.skuId
      const qty = goods.count
      console.log(goodId)
      console.log(qty)
      const memberId = userStore.userInfo.data.user.id
      // 登录之后加入购物车逻辑
      await addCartListAPI({ memberId, goodId, qty })
      updateCartList()
    }
    // 删除购物车商品
    const deleteCart = async (ids) => {
      await deleteCartListAPI([ids])
      updateCartList()
    }
    // 计算总数
    const allCount = computed(() => {
      return cartList.value.reduce((sum, item) => sum + item.qty, 0)
    })
    // 计算总价
    const allPrice = computed(() => {
      return cartList.value.reduce(
        (sum, item) => sum + item.qty * item.good.price,
        0
      )
    })
    // 单选功能
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.goodId === skuId)
      item.selected = selected
    }
    // 全选功能
    const allCheck = (selected) => {
      cartList.value.forEach((item) => {
        item.selected = selected
      })
    }
    // 是否全选计算属性
    const isAll = computed(() => {
      return cartList.value.every((item) => item.selected)
    })
    // 购物车勾选数量
    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.qty, 0)
    })
    // 购物车勾选总价
    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.qty * item.good.price, 0)
    })
    // 改变商品数量
    const changeCount = async (skuId, count) => {
      const item = cartList.value.find((item) => item.goodId === skuId)
      item.qty = count
      await updateCartListAPI(item)
    }
    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }
    return {
      addCart,
      cartList,
      deleteCart,
      allCount,
      allPrice,
      singleCheck,
      allCheck,
      isAll,
      selectedCount,
      selectedPrice,
      changeCount,
      clearCart,
      updateCartList
    }
  },
  { persist: true }
)
